import { CanActivate, ExecutionContext, HttpException, Injectable, UnauthorizedException } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { Reflector } from '@nestjs/core';
import { JwtService, TokenExpiredError } from '@nestjs/jwt';
import { Request } from 'express';
import { Observable } from 'rxjs';
import { ConfigEnum } from '../../enum/config.enum';
import { IS_PUBLIC_KEY } from '../../decorators/public.decorator';

@Injectable()
export class AuthGuard implements CanActivate {
  constructor(
    private jwtService: JwtService,
    private reflector: Reflector,
    private configService: ConfigService
  ) {}

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const isPublic = this.reflector.getAllAndOverride(IS_PUBLIC_KEY, [
      context.getHandler(),
      context.getClass(),
    ])
    if (isPublic) {  // 跳过验证
      return true;
    }

    const request = context.switchToHttp().getRequest();
    // console.log("🚀 ~ AuthGuard ~ request:", request.headers)
    const token = this.extractTokenFromHeader(request);
    if (!token) {
      throw new UnauthorizedException('Token 未提供。');
    }
    try {
      const secret = this.configService.get(ConfigEnum.JWT_SECRET)
      const payload = await this.jwtService.verifyAsync(
        token, { secret}
      )
      // console.log("🚀 ~ AuthGuard ~ payload:", payload)
      request['user'] = payload;
    } catch (error) {
      // throw new HttpException(error, 401);
      if (error instanceof TokenExpiredError) {
        // 处理 Token 过期
        throw new HttpException('Token 已过期，请重新登录。', 401);
      } else {
        // 处理其他类型的错误
        throw new HttpException('无效的 Token。', 401);
      }
    }
    return true;
  }

  private extractTokenFromHeader(request: Request): string | undefined {
    const [type, token] = request.headers.authorization?.split(' ') ?? [];
    return type === 'Bearer' ? token : undefined;
  }
}
